import React from 'react';
import { Space,Radio,Modal ,Select , Table, Button, Form, Input, message, DatePicker, Dropdown,Tag, Drawer,Row,Col,Pagination} from 'antd';
import {EyeOutlined,SettingOutlined,DownOutlined,} from '@ant-design/icons';

import { addUserApi, getUserApi, roleApi, delUserApi,alterUserApi } from '../../apis/users';
import { useNavigate } from 'react-router-dom';
const { RangePicker } = DatePicker;
const { Option } = Select;
export default function UserPage() {
  const [selectedRowKeys, setSelectedRowKeys] = React.useState([]);
  const [dataList,setDataList] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [open, setOpen] = React.useState(false);
  const [isModalOpen, setIsModalOpen] = React.useState(false);
  const [searchUser,setSearchUser] = React.useState({});
  const [roleList,setRoleList] = React.useState([]);
  const [pageTotal, setPageTotal] = React.useState(0);
  const [drawerTitle,setDrawerTitle] = React.useState("");
  const [userId,setUserId] = React.useState("");
  function showModal(){
    setIsModalOpen(true);
  };
  const handleOk = () => {
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  function getData(params) {
    getUserApi(params).then(res=>{
      // console.log('res',res.rows);
      setLoading(false);
      setDataList(res.rows);
      setPageTotal(res.total)
    });
  }
  React.useEffect((params)=>{
    setLoading(true);
    getData(params)
  },[]);
  // 点击查看用户信息
  function doSearch(par){
    setSearchUser(par);
    showModal();
  }
  //修改page页面效果
  function onPageChange(pageNumber, pageSize) {
    const pageNum = pageNumber
    getData({ pageNum, pageSize })
  }
  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '性别',
      dataIndex: 'ssex',
      key: "ssex",
      filters: [{ text: '男', value: '0' }, { text: "女", value: '1' }, { text: "保密", value: '2' }],
      onFilter: (value, record) => record.ssex === value,
      render(text) {
        switch (text) {
          case "0":
            return "男";
          case "1":
            return "女"
          default: return "保密"
        }
      },
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },
    {
      title: '部门',
      dataIndex: 'deptName',
    },
    {
      title: '电话',
      dataIndex: 'mobile',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (status) => status == '1' ? <Tag color="red">有效</Tag> : <Tag color="green">无效</Tag>
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      render: (item) => (
        <Space size="middle">
          <EyeOutlined onClick={()=>doSearch(item)} style={{color:'#4ea1f5'}}/>
          <SettingOutlined onClick={()=>showDrawer2(item)} style={{color:'#4fbd8b'}}/>
        </Space>
      ),
    },
  ];
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
const items = [
  {
    key: '1',
    label: '密码重置',
  },
  {
    key: '2',
    label: '导出Excel',
  },
];
const menuProps = {
  items,
  onClick: handleMenuClick,
};
  // const onSelectChange = (newSelectedRowKeys) => {
  //   console.log('selectedRowKeys changed: ', newSelectedRowKeys);
  //   setSelectedRowKeys(newSelectedRowKeys);
  // };
  
  const navigate = useNavigate();
    // const [loading,setLoading] = React.useState(false);
  const searchFinish = (values) => {
      // console.log('Success:', values);
      const { username, deptId, rangePicker } = values;
      if (rangePicker) {
        const createTimeFrom = moment(rangePicker[0].$d).format("YYYY-MM-DD");
        const createTimeTo = moment(rangePicker[1].$d).format("YYYY-MM-DD");
        getData({ username, deptId, createTimeFrom, createTimeTo })
      }
      else {
        getData({ username, deptId })
      }
  };
  const searchFinishFailed = (errorInfo) => {
      console.log('Failed:', errorInfo);
  };
  function handleMenuClick(e){
    message.info('Click on menu item.');
    console.log('click', e);
  };
  const [addForm] = Form.useForm();
  // 点击新增、
  function showDrawer(par){
    // 渲染新增的Form
    roleApi().then(res => {
      // console.log('res',res.rows);
      res.rows.forEach(item => {
        let o = {label:item.roleName,value:item.roleId};
        roleList.push(o);
        // console.log('it',item);
      })
      setRoleList([...roleList]);
    });
    // console.log("par",par);
    // if(par.userId){
    //   // 编辑
    // }else{
    //   // 新增
    // }
    setDrawerTitle("新增用户");
    setOpen(true);
    // addForm.resetFieldsValue({})
  };
  //点击编辑
  function showDrawer2(par){
    console.log("par",par);
    setUserId(par.userId)
    setDrawerTitle("编辑用户");
    setOpen(true);
    addForm.setFieldsValue({
      ...par, 
      roleId:par.roleId?.split(',').map(item=>~~item)
    })
  }
  
  function onClose(){
    setOpen(false);
  };
  const onFinish = (values) => {
    console.log('Success:', values);
    console.log(drawerTitle);
    if(drawerTitle=="新增用户"){
      addUserApi({...values,roleId:values.roleId.join()}).then(res => {
        // console.log('res',res);
        message.success("新增成功")
        setOpen(false);
        getData();
      }).catch(err => {
        console.log('err',err);
      })
    }else{
      if(!values.mobile){
        delete values.mobile;
      }
      if(!values.email){
        delete values.email;
      }
      
      console.log("values",values);
      alterUserApi({...values,roleId:values.roleId.join(),userId}).then(res => { 
        message.success("修改成功");
        getData();
      }).catch(err => {
        console.log('err',err);
      })
    }
    
  };
  const onFinishFailed = (errorInfo) => {
      console.log('Failed:', errorInfo);
  };
  const onDeptChange = (value) => {
    console.log('value',value);
  };
  const onRoleChange = (value) => {
    // console.log('value',value);
  };
  const onGenderChange = (value) => {
    console.log(value)
  };

  function onSelectChange(newSelectedRowKeys){
    // console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  }
  // 删除
  const [deleteModalOpen,setDeleteModalOpen]=React.useState(false)
  function delUser(){
    setDeleteModalOpen(true);
  }
  const deleteOk = () => {
    setDeleteModalOpen(false);
    if(selectedRowKeys.length===0){
      console.log(selectedRowKeys)
    }
    else {
      message.success("删除成功")
      delUserApi(selectedRowKeys)
    }
    getData()
  };
  const deleteCancel = () => {
    setDeleteModalOpen(false);
  };
  return (
    <div>
      <Form 
      labelCol={{span: 5}}
      wrapperCol={{span: 10}}
      initialValues={{remember: true}}
      onFinish={searchFinish}
      onFinishFailed={searchFinishFailed}
      layout='horizontal '>
        <Row>
            <Col span={12}>
              <Form.Item label="用户名" name="username">
                  <Input/>
              </Form.Item>
              <Form.Item name="rangePicker" label="创建时间">
                <RangePicker />
              </Form.Item>
            </Col>
            <Col span={12}>
            <Form.Item
                name="deptId"
                label="部门"
              >
                <Select
                  onChange={onGenderChange}
                >
                  <Option value="0">全部部门</Option>
                  <Option value="1">开发部</Option>
                  <Option value="2">开发一部</Option>
                  <Option value="6">测试部</Option>
                  <Option value="4">市场部</Option>
                  <Option value="5">人事部</Option>
                </Select>
              </Form.Item>
              <Form.Item wrapperCol={{offset: 8,span: 16}}>
                  <Button className='b-s' type="primary" htmlType="submit" loading={loading}>查询</Button>
                  <Button className='b-s'  htmlType="submit" loading={loading}>重置</Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
        <div>
        <Button className='b-s' onClick={showDrawer}>新增</Button>
        <Button className='b-s' onClick={delUser} style={{margin:'0 10px 20px'}}>删除</Button>
          <Dropdown menu={menuProps}>
            <Button className='b-s'>
              <Space>
                更多操作
                <DownOutlined />
              </Space>
            </Button>
          </Dropdown>
        </div>
      <Table pagination={false} loading={loading} rowKey='userId' rowSelection={rowSelection} columns={columns} dataSource={dataList} />
      <Pagination
            style={{ float: "right" }}
            total={pageTotal}
            showSizeChanger
            showQuickJumper
            onChange={onPageChange}
            showTotal={(total) => `显示 1 ~ 10 条记录,一共 ${total} 条数据`}
          />
      {/* 新增，编辑 */}
      <Drawer
      closable={false}
      placement="right"
      title={drawerTitle}
      width={500}
      onClose={onClose}
      open={open}>
        <Form labelCol={{span: 8}}
        wrapperCol={{span: 16}}
        initialValues={{remember: true}}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        form={addForm}>
            <Form.Item label="用户名" name="username"
            rules={[{required: true}]}>
                <Input/>
            </Form.Item>
            {
              drawerTitle=="新增用户"  &&  <Form.Item label="密码" name="password" initialValue={"1234qwer"}>
                    <Input disabled={true}/>
                  </Form.Item>
            }
            <Form.Item label="邮箱" name="email">
                <Input/>
            </Form.Item>
            <Form.Item label="电话" name="mobile">
                <Input/>
            </Form.Item>
            <Form.Item label="角色" name="roleId"
            rules={[{required: true}]}>
              <Select mode="multiple" allowClear
              style={{width: '100%'}}
              // placeholder="Please select"
              // defaultValue={['a10', 'c12']}
              onChange={onRoleChange}
              options={roleList}/>
            </Form.Item>
            <Form.Item name="deptId" label="部门">
              <Select onChange={onDeptChange} allowClear>
                {/* value为部门id */}
                <Option value="0">全部部门</Option>
                <Option value="1">开发部</Option>
                <Option value="2">开发一部</Option>
                <Option value="6">测试部</Option>
                <Option value="4">市场部</Option>
                <Option value="5">人事部</Option>
              </Select>
            </Form.Item>
            <Form.Item label="状态" name="status"
            rules={[{required: true}]}>
              <Radio.Group>
                <Radio value="0"> 锁定 </Radio>
                <Radio value="1"> 有效 </Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item label="性别" name="ssex"
            rules={[{required: true}]}>
                <Radio.Group>
                <Radio value="0"> 男 </Radio>
                <Radio value="1"> 女 </Radio>
                <Radio value="2"> 保密 </Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item wrapperCol={{offset: 8,span: 16,}}>
                <Button onClick={onClose} loading={loading}>取消</Button>
                <Button type="primary" htmlType="submit" loading={loading} >确认</Button>
            </Form.Item>
        </Form>
      </Drawer>
      {/* 用户信息详情模态框 */}
      <Modal title="用户信息" width={750} footer={null} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <div style={{display:'flex',padding:'20px 10px'}}>
          <img style={{width:'115px',height:'115px',marginRight:'55px'}} src={'http://xawn.f3322.net:8002/distremote/static/avatar/'+searchUser.avatar} alt="" />
          <div style={{display:'flex'}}>
            <ul style={{lineHeight:'30px',marginRight:'50px'}}>
              <li>账户：{searchUser.username}</li>
              <li>角色：{searchUser.roleName}</li>
              <li>性别：{searchUser.ssex}</li>
              <li>电话：{searchUser.mobile}</li>
              <li>邮箱：{searchUser.email}</li>
            </ul>
            <ul style={{lineHeight:'30px'}}>
              <li>部门：{searchUser.deptName}</li>
              <li>状态：{searchUser.status == '1' ? <Tag color="red">有效</Tag> : <Tag color="green">无效</Tag>}</li>
              <li>创建时间：{searchUser.createTime}</li>
              <li>最近登录：{searchUser.lastLoginTime}</li>
              <li>描述：{searchUser.description}</li>
            </ul>
          </div>
        </div>
      </Modal>
      {/* 显示是否删除模态框 */}
      <Modal title="确定是否删除所选择的数据？"  open={deleteModalOpen} onOk={deleteOk} onCancel={deleteCancel}>
        <p>当您点击确定按钮后，这些记录将会被彻底删除</p>
      </Modal>
    </div>
  )
}
